<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear='getUserlist'>
            <el-button slot="append" icon="el-icon-search" @click="getUserlist"></el-button>
          </el-input>
        </el-col>
        <!-- 第二列 -->
        <el-col :span="6">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
          <!-- 表格区域 -->
     <el-table
      :data="userlist"
       stripe
       border
      >
       <el-table-column
        type="index"
        >
      </el-table-column>
      <el-table-column
        prop="username"
        label="姓名"
        >
      </el-table-column>
      <el-table-column
        prop="email"
        label="邮箱"
        >
      </el-table-column>
      <el-table-column
        prop="mobile"
        label="电话">
      </el-table-column>
       <el-table-column
        prop="role_name"
        label="角色">
      </el-table-column>
       <el-table-column
        label="状态">
        <!-- 模板插槽 -->
        <template slot-scope="scope">
          <!-- {{scope.row}} -->
          <!-- 是scop的属性,可以得到当前项的数据 -->
          <el-switch
          v-model="scope.row.mg_state"
          active-color="#409EFF"
          inactive-color="#ccc" @change="userStateChange(scope.row)">
</el-switch>

        </template>
      </el-table-column>
       <el-table-column
        label="操作" width="180px">
        <template slot-scope="scope">
        <!-- 操作插槽 -->
        <!-- 编辑按钮 -->
        <!-- scope.row就是这一行用户的信息,.id就获得了本行数据的id -->
        <el-button type="primary" icon="el-icon-edit" size="mini" 
        @click="showEditDialog(scope.row.id)"></el-button>
        <!-- 删除按钮 -->
        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
        <!-- 设置按钮 -->
         <el-tooltip class="item" effect="dark" content="分配角色" placement="top" 
         :enterable='false'>
              <el-button type="warning" icon="el-icon-s-tools" size="mini"></el-button>
    </el-tooltip>
    </template>
      </el-table-column>
    </el-table>
        <!-- 分页按钮 -->
  <div class="block">
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>


    </el-card>
<!-- 添加用户对话框 -->
    <el-dialog
  title="添加用户"
  :visible.sync="dialogVisible"
  width="50%"
  @close = 'resetForm'>
  <!-- 主体区域 -->
<el-form :model="addForm" ref="addFormRef" :rules="formRules"   label-width="80px">
  <!-- 用户名 -->
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
<!-- 密码 -->
    <el-form-item label="密码" prop="password">
    <el-input v-model="addForm.password" type="password"></el-input>
  </el-form-item>
  <!--邮箱  -->
    <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>

  <!-- 手机 -->
    <el-form-item label="手机" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>

</el-form>
    <!-- 底部区域 -->
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<!-- 编辑对话框 -->
<el-dialog
  title="编辑用户"
  :visible.sync="editDialogVisible"
  width="50%"
   @close = "editDialogClosed">
  <!-- 编辑对话框 -->
<el-form :model="editForm" :rules="formRules" ref="editFormRef" label-width="80px">
  <!-- 用户名 -->
  <el-form-item label="用户名">
    <el-input v-model="editForm.username" disabled></el-input>
  </el-form-item>
    <!-- 邮箱 -->
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="editForm.email"></el-input>
  </el-form-item>
  <!-- 手机号 -->
  <el-form-item label="手机号" prop="mobile">
    <el-input v-model="editForm.mobile"></el-input>
  </el-form-item>


</el-form>  
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editDialogInfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
import { async } from 'q';
export default {
  name: 'Users',
  data() {
                // 验证邮箱规则
          const checkEmail = (rule, value, cb) => {
            let regEmail =  /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/

            if (regEmail.test(value)) {
          cb()
    } else {
      cb(new Error('邮箱格式不正确'))
    }

          }
      // 验证手机号
        const checkmobile = (rule, value, cb) => {
           let regmobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
          if (regmobile.test(value)) {
          cb()
    } else {
      cb(new Error('手机号码格式不正确'))
    }

      }

    return {
     queryInfo:{
      query: '',
      // 当前处于第几页
      pagenum: 1,
      //当前每页显示多少条数据
      pagesize: 2
     },
     //用户列表
      userlist:[],
      //查询到的用户信息
      editForm:{},
      total: 0,
        dialogVisible: false,
        // 编辑用户
        editDialogVisible:false,

        // 添加用户的表单数据
        addForm:{
          username:'',
          password:'',
          email:'',
          mobile:''
        },
        // 添加用户表单验证规则对象
        formRules:{
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' }, { min: 1, max: 7, message: '长度在 1 ~ 7 个字符', trigger: 'blur' }
          ],
          password:[
             { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 8, message: '长度在 6 ~ 8 个字符', trigger: 'blur' }
          ],
                    email:[
             { required: true, message: '请输入邮箱', trigger: 'blur' }, { validator: checkEmail, trigger: 'blur' }
          ],
                    mobile:[
             { required: true, message: '请输入手机号', trigger: 'blur' },{ validator: checkmobile, trigger: 'blur' }

          ]
        }
        }
      },
  created() {
    this.getUserlist()
  },
  // 获取用户列表数据
  methods: {
    async getUserlist() {
     const {data:res} =await this.$http.get('users',{params:this.queryInfo})//第一个参数是地址,第二个是参数
    //  console.log(res)
    if (res.meta.status != 200) {
      return this.$message.error('获取用户列表失败')
    }
    //没有return说明获取用户列表成功
    this.userlist = res.data.users
    this.total = res.data.total
    },
    // 监听pagesize改变的事件
      handleSizeChange(newSize) {
        // console.log(`每页 ${newSize} 条`)
        
        this.queryInfo.pagesize = newSize
        //重新获取用户列表
        this.getUserlist()
      },
      //监听页码值该改变的事件
      handleCurrentChange(newPage) {
        // console.log(`当前页: ${newPage}`)
        this.queryInfo.pagenum = newPage
        //重新获取用户列表
         this.getUserlist()
      },
      //监听 switch 开关状态的改变
    async userStateChange(userinfo){
        console.log(userinfo)
        //发送请求
     const {data:res} = await  this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
    //  console.log(res)
    if(res.meta.status != 200){
      return this.$message.error('更新用户状态失败!')
    }
    this.$message.success('更新用户状态成功')
      },
      //关闭之后重置表单
      resetForm(){
        this.$refs.addFormRef.resetFields()
      },
      //添加用户预校验
      addUser(){
         this.$refs.addFormRef.validate(async valid => {
          if (!valid) return//错误直接return
          //预校验通过之后发送网络请求添加用户
       const {data:res} = await this.$http.post('users',this.addForm)
       if(res.meta.status != 201) {
         return this.$message.error('添加用户失败')
       }
       this.$message.success('添加用户成功')
       //成功之后隐藏窗口
       this.dialogVisible = false
      //  重新加载用户列表数据
      this.getUserlist()
        })
      },
    async showEditDialog(id){//显示对话框的时候获取id,从修改按钮的单击事件中传进来
        // console.log(id)
        const {data:res} = await this.$http.get('users/'+id)
        // console.log(res)
        if(res.meta.status != 200) return this.$message.error('获取用户信息失败')
        this.editForm = res.data
        console.log(this.editForm)
        this.editDialogVisible = true 
      },
      //监听修改用户对话框的关闭事件
      editDialogClosed(){
        this.$refs.editFormRef.resetFields()
      },
      //编辑表单预校验
      editDialogInfo(){
         this.$refs.editFormRef.validate(async valid => {
           if(!valid) return
           const {data:res} = await this.$http.put('users/'+this.editForm.id,{email:this.editForm.email,mobile:this.editForm.mobile})
           if(res.meta.status!=200) return this.$message.error('编辑用户信息失败')
           this.$message.success('编辑用户信息成功')
           //关闭对话框
           this.editDialogVisible = false
           //从新加载页面
           this.getUserlist()

        })
      },
      // 删除用户
     async removeUser(id){
        // console.log(id)
          const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // console.log(confirmResult) //confirm cancel
        if(confirmResult != 'confirm') return this.$message.info('已取消删除')
        //成功发送删除用户的请求
               const {data:res} = await this.$http.delete('users/'+id)
       if(res.meta.status != 200) {
         return this.$message.error('删除用户信息失败')
         }
       this.$message.success('删除用户信息成功')
       //从新加载页面
       this.getUserlist()

      }
  }
}
</script>

<style lang="less" scoped>
</style>